<template>
  <div class="w-full">
    <a-form-model ref="formData" :model="formData" :rules="rules" v-bind="layout">
      <a-form-model-item has-feedback label="用户名">
        <a-input disabled v-model="formData.userLoginName"></a-input>
      </a-form-model-item>
      <a-form-model-item has-feedback label="短信验证码">
        <a-input v-model="formData.code" style="width: 78%"></a-input>
        <a-button type="primary" class="tips-btn" :disabled="formData.sendCode!=''" style="width: 20%;margin-left: 2%;" @click="sendCode()">{{tips}}</a-button>
      </a-form-model-item>
      <a-form-model-item has-feedback label="原始手机号" prop="oldMobilephone">
        <a-input disabled v-model="formData.oldMobilephone" placeholder="未查询到原始手机号，请联系管理员"></a-input>
      </a-form-model-item>
      <a-form-model-item has-feedback label="新手机号" prop="newMobilephone">
        <a-input v-model="formData.newMobilephone"></a-input>
      </a-form-model-item>
      <a-form-model-item has-feedback label="确认新手机号" prop="confirmMobilephone">
        <a-input v-model="formData.confirmMobilephone"></a-input>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import dapProjectService from '@/api/dapProjectService'
import orupService from '@/api/orupService'
import JSEncrypt from 'jsencrypt'

export default {
  name: 'PersonalSetting',
  data () {
    const validateOldPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入原始手机号'))
      } else {
        if (this.formData.newMobilephone !== '') {
          this.$refs.formData.validateField('newMobilephone')
        }
        callback()
      }
    }
    const validateNewPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新手机号'))
      } else if (value != '' && this.formData.newMobilephone == this.formData.oldMobilephone) {
        callback(new Error('新旧手机号不能一致'))
      } else {
        var reg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
        if(!reg.test(value)){
          callback(new Error('新手机号格式有误！'))
        }
        if (this.formData.confirmMobilephone !== '') {
          this.$refs.formData.validateField('confirmMobilephone')
        }
        callback()
      }
    }
    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认新手机号'))
      } else if (value !== this.formData.newMobilephone) {
        callback(new Error('两次手机号不一致'))
      } else {
        callback()
      }
    }
    return {
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      formData: {
        code: '',
        sendCode: '',
        userLoginName: '',
        oldMobilephone: '',
        newMobilephone: '',
        confirmMobilephone: ''
      },
      rules: {
        oldMobilephone: [{ validator: validateOldPass, trigger: 'change' }],
        newMobilephone: [{ validator: validateNewPass, trigger: 'change' }],
        confirmMobilephone: [{ validator: validateConfirmPass, trigger: 'change' }]
      },
      count: 120,
      tips: '发送'
    }
  },
  components: {},
  created () {
  },
  mounted () {
    this.formData.userLoginName = this.userInfo.userName
    this.formData.oldMobilephone = this.userInfo.mobilephone
  },
  computed: {},
  methods: {
    updateMobilephone (ctl) {
      if (!this.formData.code) {
        this.$warning({ content: '请输入短信验证码' })
        return
      } else if (this.formData.code != this.formData.sendCode) {
        this.$warning({ content: '短信验证码错误' })
        return
      }
      this.$refs['formData'].validate(valid => {
        if (valid) {
          orupService.updateMobilephone({
            oldPhone: this.formData.oldMobilephone,
            newPhone: this.formData.newMobilephone,
            userId: this.userInfo.id
          }).then(data => {
            if (data == '修改成功!') {
              ctl.closeDialog();
              this.$success({ content: data });
            } else {
              this.$warning({ content: data });
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    createCode(){
      return Math.floor(Math.random()*4000+1000);
    },
    encryptCode (code) {
      const je = new JSEncrypt()
      je.setPublicKey('MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIjB97HPED0yxZoi9vxrETw4s/OGrrho26Piyn8GdAMBdMOdpQm8981zHK5nSAollJajQZk1YApxHMiEGEtNjkkCAwEAAQ==')
      return '{rsa}' + je.encrypt(code)
    },
    sendCode(){
      this.formData.sendCode = this.createCode();
      let param = {
        userId: this.userInfo.id,
        code: this.encryptCode(this.formData.sendCode+''),//前端加密，后端解密
        templateCode: 'SMS_167465353'
      }
      dapProjectService.sendCode(param).then((d) => {
        if(d == '短信发送成功！'){
          this.setInterval();
          this.$success({ content: '短信验证码发送成功' })
        }else{
          this.formData.sendCode = '';
          this.$warning({ content: d.message || d })
        }
      })
    },
    setInterval(){
      let _this = this;
      let timer = setInterval(function(){
        _this.count--;
        if(_this.count<=0){
          _this.formData.sendCode = '';
          _this.tips = '发送';
          clearInterval(timer);
        }else{
          _this.tips = _this.count + '秒有效';
        }
      }, 1000)
    }
  }
}
</script>

<style scoped lang="less">
.personal-setting{
  display: flex;
  color: white;
  align-items: center;
  font-size: 16px;
  i{
    margin-left: 10px;
    cursor: pointer;
  }
}
</style>
<style>
.showConfirm{
  margin-bottom: 0;
  line-height: 30px;
  color: red;
}
</style>
